package com.huzz.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huzz.entity.SysSecondAuth;
import com.huzz.mapper.SysSecondAuthMapper;
import com.huzz.service.ISysSecondAuthService;
import com.huzz.util.body.DataBox;
import com.huzz.util.encryption.RSAUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Name 名称
 * @Description 描述
 * @Author 童年的纸飞机
 * @Since 2023-04-2023/4/27 08:55
 */
@Service
public class SysSecondAuthServiceImpl extends ServiceImpl<SysSecondAuthMapper, SysSecondAuth> implements ISysSecondAuthService {

    @Value("${encryption.rsa.publicKey}")
    private String publicKey;

    @Value("${encryption.rsa.privateKey}")
    private String privateKey;

    @Autowired
    private SysSecondAuthMapper secondAuthMapper;

    @Override
    public DataBox<String> createSecondAuth(String service, String secondPassword, String description, Integer safeTime) {
        if (StringUtils.isNotEmpty(service) && StringUtils.isNotEmpty(secondPassword) ) {
            if (ObjectUtils.isNotEmpty(secondAuthMapper.selectOne(Wrappers.<SysSecondAuth>lambdaQuery().eq(SysSecondAuth::getService, service)))) {
                return DataBox.failedBuilder("该service已存在, 新建失败");
            }
            String encryption = RSAUtils.encryption(secondPassword, publicKey);
            SysSecondAuth sysSecondAuth = SysSecondAuth.builder().service(service).secondPassword(encryption).description(description).safeTime(safeTime).build();
            return DataBox.builder(secondAuthMapper.insert(sysSecondAuth) > 0, "新建成功", "新建失败");
        }
        return DataBox.failedBuilder("业务名称标识和密码不能为空");
    }

    @Override
    public List<SysSecondAuth> findSecondAuthList() {
        return secondAuthMapper.selectList(null);
    }

    @Override
    public DataBox<String> updateSecondAuthById(Integer id, String secondPassword, String description, Integer safeTime) {
        if (id != null) {
            if (StringUtils.isNotEmpty(secondPassword)) {
                secondPassword = RSAUtils.encryption(secondPassword, publicKey);
            }
            return DataBox.builder(secondAuthMapper.updateById(SysSecondAuth.builder()
                    .id(id).secondPassword(secondPassword).description(description).safeTime(safeTime)
                    .build()) > 0, "更新成功", "更新失败");
        }

        return DataBox.failedBuilder("id不能为空");
    }
}
